package com.grwx.omc.exception;

import com.grwx.omc.constant.Constant;
import com.grwx.omc.constant.RestCodeConstants;
import com.grwx.omc.entity.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author jay
 * @description 全局异常处理
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 校验异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseData handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        String defaultMessage = fieldErrors.get(0).getDefaultMessage();
        return ResponseData.error(defaultMessage);
    }

    @ExceptionHandler(BaseException.class)
    public ResponseData handleBaseException(BaseException e){
        log.error(e.getMessage());
        return ResponseData.error(e.getStatus(),e.getMessage());
    }

    @ExceptionHandler(ValidationException.class)
    public ResponseData handleValidationException(ValidationException e) {
        log.error(e.getMessage());
        return ResponseData.error(e.getStatus(),e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResponseData handleOtherException(Exception e) {
        log.error(e.getMessage());
        return ResponseData.error(RestCodeConstants.INNER_ERROR_CODE, Constant.MsgCode.INNER_ERROR);
    }
}
